package com.interfaces.wx;

import com.alibaba.fastjson2.JSONObject;
import com.interfaces.config.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/***
 * 微信公众号授权登录TOKEN
 */
public class WxAuthAccessToken {

    /**
     *  密钥
     */
    //获取ACCESS_TOKEN
    private static String ACCESS_TOKEN_URL="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    //刷新ACCESS_TOKEN
    private static String REFRESH_TOKEN_URL="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
    //获取用户OPENID
    private static String SNSAPI_BASE="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    //获取用户信息
    private static String SNSAPI_USERINFO_URL="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    //校验ACCESS_TOKEN是否有效
    private static String VERIFY_ACCESS_TOKEN_URL="https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID";

    /***
     * 获取登录用的accessToken
     */
    public JSONObject accessToken(String code,RedisCache cache) {
        ACCESS_TOKEN_URL = ACCESS_TOKEN_URL.replaceAll("APPID", WxPayInit.APPID).replaceAll("SECRET", WxPayInit.SECRET);
        ACCESS_TOKEN_URL = ACCESS_TOKEN_URL.replaceAll("CODE", code);
        if(cache.isContainsKey("ACCESS_TOKEN_JSON")&&cache.isTimeOut("ACCESS_TOKEN_JSON")){
            //存在缓存且未过期
            JSONObject jsonObject =cache.getCacheObject("ACCESS_TOKEN_JSON");
            String access_token=jsonObject.getString("access_token");
            JSONObject userInfoResult = SnsApiUserInfo(access_token, jsonObject.getString("openid"));
            if(null == userInfoResult.get("openid")&&null!=userInfoResult.get("errcode")){
                if(42001==userInfoResult.getInteger("errcode")){
                    cache.deleteObject("ACCESS_TOKEN_JSON");
                }
                String result = WechatMsg.doGetPost(ACCESS_TOKEN_URL, "GET", null);
                JSONObject jsonObjects = JSONObject.parseObject(result);

                if (null != jsonObjects.get("openid") && null != jsonObject.get("access_token")) {
                    //存入缓存
                    cache.putCacheObject("ACCESS_TOKEN_JSON",jsonObject,jsonObject.getInteger("expires_in")*1000, TimeUnit.SECONDS);
                    String access_tokens=jsonObject.getString("access_token");
                    JSONObject userInfoResults = SnsApiUserInfo(access_tokens, jsonObject.getString("openid"));
                    return userInfoResults;
                }else{
                    return jsonObject;
                }
            }
            return userInfoResult;
        }else{
            String result = WechatMsg.doGetPost(ACCESS_TOKEN_URL, "GET", null);
            JSONObject jsonObject = JSONObject.parseObject(result);

            if (null != jsonObject.get("openid") && null != jsonObject.get("access_token")) {
                //存入缓存
                cache.putCacheObject("ACCESS_TOKEN_JSON",jsonObject,jsonObject.getInteger("expires_in")*1000, TimeUnit.SECONDS);
                String access_token=jsonObject.getString("access_token");
                JSONObject userInfoResult = SnsApiUserInfo(access_token, jsonObject.getString("openid"));
                return userInfoResult;
            }else{
                return jsonObject;
            }
        }

    }

    public static JSONObject SnsApiUserInfo(String ACCESS_TOKEN, String OPENID){
        SNSAPI_USERINFO_URL=SNSAPI_USERINFO_URL.replace("ACCESS_TOKEN",ACCESS_TOKEN).replace("OPENID",OPENID);
        String result=WechatMsg.doGetPost(SNSAPI_USERINFO_URL,"GET",null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }
}
